package hos.kotlin

/**
 * <p>Title: UrlUitls </p>
 * <p>Description:  </p>
 * <p>Company: www.mapuni.com </p>
 *
 * @author : 蔡俊峰
 * @date : 2024-07-11 19:16
 * @version : 1.0
 */
object UrlUtils {
    @JvmStatic
    @JvmOverloads
    fun url(target: String?, value: String = ""): String {
        if (target == null || target.isNull()) {
            return value
        }
        return if (target.contains("?")) {
            target.split("?")[0]
        } else {
            target
        }
    }
    @JvmStatic
    @JvmOverloads
    fun splitHttp(target: String?, isHttp: Boolean = true): String {
        if (target == null || target.isNull()) {
            return ""
        }
        if (target.contains("http://") || target.contains("https://")) {
            return target;
        }
        if (isHttp) {
            return "http://$target"
        }
        return "https://$target"
    }
    @JvmStatic
    private fun urlParams(params: String): Map<String, String> {
        if (params.contains("&")) {
            val param = params.split("&")
            val map = mutableMapOf<String, String>()
            param.forEach {
                val item = it.split("=")
                if (item.size == 1) {
                    map[item.first()] = ""
                } else if (item.size == 2) {
                    map[item.first()] = item.last()
                }
            }
            return map
        }
        if (params.contains("=")) {
            val map = mutableMapOf<String, String>()
            val item = params.split("=")
            if (item.size == 1) {
                map[item.first()] = ""
            } else if (item.size == 2) {
                map[item.first()] = item.last()
            }
            return map
        }
        return mutableMapOf()
    }
    @JvmStatic
    @JvmOverloads
    fun params(
        target: String?,
        params: MutableMap<String, String> = mutableMapOf()
    ): Map<String, String> {
        if (target == null || target.isNull()) {
            return params
        }
        if (!target.contains("?")) {
            return urlParams(target)
        }
        return urlParams(target.split("?")[1])
    }
}